<template>
  <el-dialog title="编辑个人信息" :visible.sync="visible">
    <el-form :model="user">
      <el-form-item label="用户名">
        <el-input v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <!-- 请替换为您的实际上传URL -->
        <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-upload="beforeAvatarUpload"
          list-type="picture-card">
          <i class="el-icon-plus"></i>
          <img v-if="user.avatar" :src="user.avatar" class="avatar">
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="saveUserInfo">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      user: {
        username: '',
        avatar: ''
      }
    };
  },
  methods: {
    handlePreview(file) {
      console.log('Preview file:', file);
    },
    handleRemove(file, fileList) {
      console.log('Remove file:', file);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    saveUserInfo() {
      // 提交用户信息的保存逻辑
      console.log('User info saved:', this.user);
      this.visible = false;
    }
  }
};
</script>

<style scoped>
.upload-demo i {
  color: #fff;
  font-size: 14px;
  background-color: #3399ff;
  border-radius: 4px;
}
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-top: 10px;
}
</style>
